package tor;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;

import org.silvertunnel.netlib.api.NetFactory;
import org.silvertunnel.netlib.api.NetLayer;
import org.silvertunnel.netlib.api.NetLayerIDs;
import org.silvertunnel.netlib.api.NetSocket;
import org.silvertunnel.netlib.layer.tor.TorHiddenServicePrivateNetAddress;
import org.silvertunnel.netlib.layer.tor.TorNetLayerUtil;
import org.silvertunnel.netlib.layer.tor.TorNetServerSocket;

public class Servx {

	/**
	 * @param args
	 * @throws IOException 
	 * @throws UnknownHostException 
	 */
	public static void main(String[] args) throws UnknownHostException, IOException {
		// TODO Auto-generated method stub
		File directory = new File("C:/klucze_olaboga/");
		TorNetLayerUtil torNetLayerUtil = TorNetLayerUtil.getInstance();
		TorHiddenServicePrivateNetAddress netAddress = torNetLayerUtil.readTorHiddenServicePrivateNetAddressFromFiles(directory, true);
		int port = 6666;
		System.out.println("Jestem.");
		org.silvertunnel.netlib.layer.tor.TorHiddenServicePortPrivateNetAddress netAddressWithPort =
	        new org.silvertunnel.netlib.layer.tor.TorHiddenServicePortPrivateNetAddress(netAddress, port);
		System.out.println("Jestem.1");
	    NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TOR);
	    System.out.println("Jestem.12");
	    netLayer.waitUntilReady();
	    System.out.println("Jestem.123");
	    TorNetServerSocket netServerSocket = (TorNetServerSocket)netLayer.createNetServerSocket(null, netAddressWithPort);
	    System.out.println("Jestem.1234");
	    while (true) {
	        final NetSocket netSocket = netServerSocket.accept();
	     // handle the new connection in an extra thread
	        new Thread() {
	            @Override
	            public void run() {
	                try {
	                    // receive data (e.g. HTTP request) and send data (e.g. HTTP response)
	                    // hint: to avoid dead locks: use separate threads for each direction
	                	System.out.println("Jestem.11111");
	                    InputStream is = netSocket.getInputStream();
	                    // ... 
	                    String ol = is.toString();
	                    System.out.println(ol);
	                    System.out.println("Jestem.xxxxxxxxxx");
	                } catch (Exception e) {
	                    e.printStackTrace();
	                } finally {
	                    try {
							netSocket.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
	                }
	            }
	        }.start();
	    }
	}

}
